var authorizeUri = IsAuthorize > 0 ? "&authorize=1&sid="+SID : "";	//授权用户发课
if(IsTeacherHelper) authorizeUri = "&courseid="+CourseID;
var editFinishButton = false;

var selectedCourse = [];//记录翻页选择的课件编号

	var SetCoursewareIDS = function(coursewareId){
		var coursewareIds = $("#selected-coursewares").val();
		var vidsArray = coursewareIds.split(",");
		vidsArray.push(coursewareId);
		$("#selected-coursewares").val(vidsArray.join(','));
	};

	
	var addCoursewareHandler = function(){
		$(".s_c_oCourseBox").unbind("hover").hover(
			function(){$(this).addClass("s_c_oCourseBox_hover");},
			function(){$(this).removeClass("s_c_oCourseBox_hover");}
		);
		
		$(".delCourseware").unbind("click").bind("click",function(){
			var cwid = $(this).attr("cwid");
			deleteCourseware(cwid);
			return false;
		});
		
		$(".editCourseware").unbind("click").bind("click",function(){
			var cwid = $(this).attr("cwid");
			editCourseware(cwid);
			return false;
		});
	};
	
	
	var editCourseware = function(coursewareid){
		var editBoxy = $.ckAjaxBoxy({
			url : "/?mod=course&act=courseware&do=edit"+authorizeUri+"&coursewareid="+coursewareid+"&courseid="+CourseID+"&tm="+new Date().getTime(),
			title : "编辑课件",
			width : 712,
			height : 620,
			callback : function(){
				$("#ajaxCancelEdit").click(function(){
					editBoxy.cancel();
				});	
				
				$("#ShowCoursewareClass").click(function(){
					$(this).hide();
					$("#CoursewareClassName").val('');
					$("#AddCoursewareClass,#CoursewareClassName").show();
				});	

				$("#AddCoursewareClass").click(function(){
					var ClassName = $("#CoursewareClassName").val();
					$.ajax({
						url : '/?mod=course&act=courseware&do=createclass'+authorizeUri,
						type : 'post',
						data : 'ClassName='+encodeURIComponent(ClassName),
						dataType : 'json',
						success : function(rs){
							if(rs.code < 0){
								alert(rs.data);
							}else{
								$("#classID").append('<option value="'+rs.code+'" selected>'+ClassName+'</option>');
								$("#AddCoursewareClass,#CoursewareClassName").hide();
								$("#ShowCoursewareClass").show();
								$('#classID').divSelect(310,"mnSelect fl mr10");
							}
						}
					});
				});

				//$('#classID').divSelect(310,"mnSelect fl mr10");   
			    
				$("#saveEdit").click(function(){
					SaveEditCourseware(SID,CourseID);
				});
				
				var SaveEditCourseware = function(SID,CourseID){
					var coursewareId = $('#saveEdit').attr('coursewareid');
					var title = $('#title').val();
					var desc = $('#videodesc').val();
					var classID = $('#classID option:selected').val();
					var CID = $('#associateClass option:selected').val();
					var className = $('#associateClass option:selected').text();
					$.ajax({
						url:'/?mod=course&act=courseware&do=update'+authorizeUri+'&sid='+SID,
						type:'post',
						data:'CoursewareID='+coursewareId+'&courseid='+CourseID+'&Title='+encodeURIComponent(title)+'&Desc='+encodeURIComponent(desc)+'&ClassID='+classID+'&CID='+CID,
						dataType:'json',
						success:function(ret) {
							if (ret.code > 0) {
								$("#ajaxCwTitle_"+ret.data.CoursewareID).text($('#title').val().substring(0, 14));
								if(className != '- 请关联课程 -'){
									$("#CwAssociate_"+ret.data.CoursewareID).replaceWith('<p class="p2" id="CwAssociate_'+ret.data.CoursewareID+'"><img alt="" src="http://res.ckimg.com/sites/www/v2/images/post/p_course_gl.gif">&nbsp;'+className+'</p>');
								}else{
									$("#CwAssociate_"+ret.data.CoursewareID).html('');
								}
								addCoursewareHandler();
								editBoxy.cancel();
							} else {
								alert(ret.data);
							}
						} 
					});
				};					
			}
		});
	};
	
	var deleteCourseware = function(coursewareid){
		$.ckConfirm({message:"确定要删除“"+$("#ajaxCwTitle_"+coursewareid).text()+"”课件吗？",ok:function(){
			//删除绑定关系
			$.ajax({
				url:'/?mod=course&act=courseware&do=unbind'+authorizeUri+'&sid='+SID,
				type:'post',
				data:'CoursewareID='+coursewareid+'&courseid='+CourseID,
				dataType:'json',
				success:function(ret) {
					if(ret.code != 0){
						alert(ret.data);
					}
				}
			});
			$("#courseware_"+coursewareid).parent().remove();
		}});
	};
	
	var updateSelectedCoursewareCount = function(){
		var cocnt = 0;
		for(var key in selectedCourse){
			if(selectedCourse[key] != null){
				cocnt = cocnt + 1;
			}
		}
		$("#selectedCoursewareCnt").text(cocnt);
	}	


	var selectCourseware = function(url){
		var selectBoxy = $.ckAjaxBoxy({
			url : url,
			title : "从课件库选择",
			width : 768,
			height : 620,
			callback : function(){
				$("#ajaxCancelSelect").click(function(){
					selectedCourse = [];
					selectBoxy.cancel();
				});
				
				$(".close").click(function(){
					selectedCourse = [];
				});
				//读取已选择的课件列表,在课件库里勾选
				$.each($("#coursewareList div.s_c_oCourseBox"),function(i,n){
					var cwid = $(this).attr("coursewareid");
					$("#co_kejian_"+cwid).attr("checked",true);
					if(selectedCourse.length == 0){
						selectedCourse.push({cwid:cwid,title:$("#courseware_"+cwid).attr('title'),ico:$("#courseware_"+cwid).attr("ico"),cn:$("#courseware_"+cwid).attr('cn')});						
					}else{
						var idfind = false;
						for(var key in selectedCourse){
							if(selectedCourse[key] != null){
								var tmp = selectedCourse[key];
								if(cwid == tmp.cwid){
									idfind = true;
									break;
								}
							}
						}
						if(idfind == false){
							selectedCourse.push({cwid:cwid,title:$("#courseware_"+cwid).attr('title'),ico:$("#courseware_"+cwid).attr("ico"),cn:$("#courseware_"+cwid).attr('cn')});
						}
					}
				});				
				
				updateSelectedCoursewareCount();
				//勾选确定和取消钱已选择的临时课件项目
				for(var cwid in selectedCourse){
					if(selectedCourse[cwid] != null){
						var obj = selectedCourse[cwid];
						$("#co_kejian_"+obj.cwid).attr("checked",true);
					}
				}
				
				$("ul.co_kejian_list input:checkbox").click(function(){
					if($(this).attr('checked') == 'checked' || $(this).attr('checked') ==  true){
						selectedCourse.push({cwid:$(this).attr('cwid'),title:$(this).attr('title'),ico:$(this).attr("ico"),cn:$(this).attr('cn')});
					}else{
						for(var key in selectedCourse){
							var tmp = selectedCourse[key];
							if(tmp != null && tmp.cwid == $(this).attr('cwid')){
								selectedCourse[key] = null;
							}
						}
					}
					
				});
				
				$("#btnSearchCourseware").click(function(){
					var docType = $(this).attr("DocType");
					var keyword = $("#inputSearchCourseware").val();
					var url = "/?mod=course&act=courseware&do=select&DocType="+docType+"&keyword="+encodeURIComponent(keyword)+authorizeUri+"&courseid="+CourseID;
					selectCourseware(url);
					return false;
				});
				

				//updateSelectedCoursewareCount();
				
				//更新已选择的课件数
				//$("#selectedCoursewareCnt").text($("#coursewareList div.s_c_oCourseBox").length);
				
				$("ul.co_kejian_list li").hover(function(){$(this).addClass("co_kejian_");}
				,function(){$(this).removeClass("co_kejian_")}).click(function(){
					updateSelectedCoursewareCount();
				});
				
				$("#fe_dialogBox a.ajaxLink").unbind("click").bind('click', function(){
					selectCourseware($(this).attr('href')+authorizeUri);
					return false;
				});

				$("#searchCourseware").inputTips();
				
				$("#saveSelect").click(function(){
					SaveSelectedCourseware(SID,CourseID);
				});	
				
				var SaveSelectedCourseware = function(SID,CourseID){
					if($("#coursewareList").length == 0){
						$("#selectedCourseware").html('<ul class="s_c_ulBox clearfix" id="coursewareList"></ul>');
					}
					
					for(var cwid in selectedCourse){
						if(selectedCourse[cwid] != null){
							var obj = selectedCourse[cwid];
							var cn = "";
							if(obj.cn !=''){
								cn = obj.cn;
							}
							
							var str = '<li>';
							str += '		<div class="s_c_oCourseBox" coursewareId="'+obj.cwid+'" id="courseware_'+obj.cwid+'" cn="'+cn+'" ico="'+obj.ico+'" title="'+obj.title+'">';
							str += '						<div class="in_type">';
							str += '							<img alt="" src="http://res.ckimg.com/sites/www/v2/images/public/kj_course/kj_'+obj.ico+'.png">';
							str += '						</div>';
							str += '						<div class="in_txt">';
							str += '							<p class="p1 f14" id="ajaxCwTitle_'+obj.cwid+'">'+obj.title.substring(0, 14)+'</p>';
							//str += '							<p class="p2" id="CwAssociate_'+obj.cwid+'">';
							if(obj.cn != ''){
								str += '<img alt="" src="http://res.ckimg.com/sites/www/v2/images/post/p_course_gl.gif">&nbsp;'+obj.cn;
							}
							str += '</p>';						
							str += '						</div>';
							str += '						<div class="in_edit">';
							str += '							<a href="javascript:;" class="editCourseware" cwid="'+obj.cwid+'">编辑</a>';
							str += '							<a target="_blank" href="/?mod=course&act=courseware&do=download&coursewareid='+obj.cwid+'">下载</a>';
							str += '							<a href="javascript:;" class="delCourseware" cwid="'+obj.cwid+'">删除</a>';
							str += '						</div>';
							str += '		</div>';
							str += '</li>';
							//避免重复添加
							if($("#courseware_"+obj.cwid).length == 0){
								$("#coursewareList").append(str);
							}
						}
					}
					//删除未选的课件
					$(".s_c_oCourseBox").each(function(i,n){
						var cwid = $(this).attr("coursewareid");
						var isRemove = true;
						for(var key in selectedCourse){
							if(selectedCourse[key] != null){
								var tmp = selectedCourse[key];
								if(tmp.cwid == cwid){
									isRemove = false;
									break;
								}
							}
						}
						if(isRemove == true){
							$("#courseware_"+cwid).parent().remove();
						}
					});
					addCoursewareHandler();
					selectedCourse = [];
					selectBoxy.cancel();	
					saveCourse(0);	
				};							
				
			}
		});		
	}
	
	var saveCourse = function(onsell){
		var cwArr = [];
		var cwStr = "";
		if($("div.s_c_oCourseBox").length > 0){
			$.each($("div.s_c_oCourseBox"),function(i,n){
				cwArr.push($(this).attr("coursewareid"));
			});
			cwStr = cwArr.join();

		}
		$.ajax({
			url:"/?mod=course&act=create&do=savecourseware"+authorizeUri,
			data:"coursewareid="+encodeURIComponent(cwStr)+"&courseid="+CourseID+"&onsell="+onsell,
			dataType:"json",
			type:"POST",
			success:function(ret){
				if(ret.code == 0){
					if(onsell == 0){
						$.ckTipsBoxy({message:"保存成功", mask:true});
						if(editFinishButton){
							document.location = "/?mod=course&act=edit&&do=editFinish&authorize="+IsAuthorize+"&sid="+SID+"&courseid="+CourseID;
						}
					}else{
						location.href = ret.data;
					}
				}else{
					$.ckTipsBoxy({message:ret.data,type:"error",width:400,height:168});
				}
			}
		});
	};	

$(function(){


	$("#uploadCourseware").click(function(){
		//初始化上传参数
		$("#coursewareId").val('');
		$.ajax({
			url:"/?mod=course&act=courseware&do=upload"+authorizeUri+"&courseid="+CourseID+"&tm="+new Date().getTime(),
			type:'get',
			dataType:'html',
			success:function(ret){
				try{
					var x = eval("("+ret+")");
					if(x.code <0){
						msgflag = true;
						$.ckAlert({message:x.data});
					}
				}catch(e){
						var uploadBoxy = $.ckAjaxBoxy({
							url : "/?mod=course&act=courseware&do=upload"+authorizeUri+"&courseid="+CourseID+"&tm="+new Date().getTime(),
							title : "上传课件",
							width : 712,
							height : 640,
							callback : function(){
								if(IsTeacherHelper) IsAuthorize = 1;
								$("#title,#videodesc").val('');
								$("#ajaxCancelUpload").click(function(){
									uploadBoxy.cancel();
								});
								$("#ajaxUploadCourseware").uploadify3({
									debug				: true,
									swf				: KK._resurl+"/common/v2/swf/uploadify-3.1.swf",
							        uploader			: KK._uploadCourseware,
									auto				: false,
									buttonClass		: 'c_btn30',
									buttonCursor		: 'hand',
									buttonImage		: '',
									buttonText		: '上传课件',
									checkExisting		: false,
									debug				: false,
									fileObjName		: 'FileData',
									fileSizeLimit		: '500MB',
									fileTypeDesc		: '',
									fileTypeExts		: '*.ppt;*.pptx;*.pps;*.dps;*.doc;*.docx;*.wps;*.xls;*.xlsx;*.et;*.rar;*.zip;*.gzip;*.txt;*.png;*.jpg;*.gif;*.jpeg;*.bmp;*.pdf;*.pot;*.rtf;*.wpt;*.dpt;*.epub;',
									formData			: {'accessserver':$.cookie.get('accessserver'), 'AuthInfo':$.cookie.get('AuthInfo'), 'SessionIDKey':$.cookie.get('SessionIDKey'), 'IsCourseware':1,'sid':SID,'authorize':IsAuthorize},
									width				: 81,
									height			: 30,
									method			: 'get',
									multi				: false,
									preventCaching	: true,
									progressData		: 'percentage',
									queueID			: 'ajaxUploadStep2',
									removeCompleted	: false,					
									
									'onSelect' : function(fileObj) {
										$("#ajaxUploadStep1").hide();
										$("#ajaxUploadStep2").show();
										$('#ajaxUploadCourseware').uploadify3('disable', true);
										$('#ajaxUploadCourseware').uploadify3('upload','*');	
									},
									onUploadError:function(file,errorCode,errorMsg,errorString){
										if(errorCode != -280){
											alert("上传失败,文件"+file.name+'，原因：'+errorMsg+errorCode);
										}
										$("#ajaxUploadStep2").html('');
										$("#ajaxUploadStep1").show();
										$('#ajaxUploadCourseware').uploadify3('disable', false);						
									},
									onCancel:function(fileObj) {
										$("#ajaxUploadStep2").html('');
										$("#ajaxUploadStep1").show();
										$('#ajaxUploadCourseware').uploadify3('disable', false);
										$('#title').val('');
									},					
									'onUploadSuccess' : function(file, data, response) {
										data = eval('('+data+')');
										if (typeof data == 'object') {
											if(data.error == 1){
												$("#coursewareId").val('v'+data.message);
												$("#ajaxUploadStep2").hide();
												$("#ajaxUploadStep3").show();	
											}else if (data.error == 2) {
												$("#coursewareId").val(data.message);
												$("#ajaxUploadStep2").hide();
												$("#ajaxUploadStep3").show();
												$('#ajaxUploadCourseware').uploadify3('disable', false);	
											} else {
												alert(data.message);
												$("#ajaxUploadStep1").show();
												$('#ajaxUploadStep2').html('');
												$('#ajaxUploadCourseware').uploadify3('disable', false);
											}
										} else {
											alert(data.message);
											$("#ajaxUploadStep2").hide();
											$('#ajaxUploadStep2').find('.inner').css('width','0px');
											$('#ajaxUploadStep2').find('.iText').html('0.00%');
											$('#ajaxUploadCourseware').uploadify3('disable', false);
										}						
									}
							    });
							    
								$("#ShowCoursewareClass").click(function(){
									$(this).hide();
									$("#CoursewareClassName").val('');
									$("#AddCoursewareClass,#CoursewareClassName").show();
								});	
				
								$("#AddCoursewareClass").click(function(){
									var ClassName = $("#CoursewareClassName").val();
									$.ajax({
										url : '/?mod=course&act=courseware&do=createclass'+authorizeUri,
										type : 'post',
										data : 'ClassName='+encodeURIComponent(ClassName),
										dataType : 'json',
										success : function(rs){
											if(rs.code < 0){
												alert(rs.data);
											}else{
												$("#classID").append('<option value="'+rs.code+'" selected>'+ClassName+'</option>');
												$("#AddCoursewareClass,#CoursewareClassName").hide();
												$("#ShowCoursewareClass").show();
												//$('#classID').divSelect(310,"mnSelect fl mr10");
											}
										}
									});
								});
				
								//$('#classID').divSelect(310,"mnSelect fl mr10");   
							    
								$("#saveBtn").click(function(){
									SaveCourseware(SID,CourseID);
								});
								
								var SaveCourseware = function(SID,CourseID){
									var coursewareId = $('#coursewareId').val();
									var title = $('#title').val();
									var desc = $('#videodesc').val();
									var classID = $('#classID option:selected').val();
									var className = $('#associateClass option:selected').text();
									$.ajax({
										url:'/?mod=course&act=courseware&do=update'+authorizeUri+'&sid='+SID,
										type:'post',
										data:'CoursewareID='+coursewareId+'&courseid='+CourseID+'&Title='+encodeURIComponent(title)+'&Desc='+encodeURIComponent(desc)+'&ClassID='+classID,
										dataType:'json',
										success:function(ret) {
											if (ret.code > 0) {
												if($("#coursewareList").length == 0){
													$("#selectedCourseware").html('<ul class="s_c_ulBox clearfix" id="coursewareList"></ul>');
												}
												var cn = "";
												if(className != '- 请关联课程 -'){
													cn = className;
												}
												var str = '<li>';
												str += '		<div class="s_c_oCourseBox" coursewareId="'+ret.data.CoursewareID+'" id="courseware_'+ret.data.CoursewareID+'" cn="'+className+'" ico="'+ret.data.IcoType+'" title="'+$('#title').val()+'">';
												str += '						<div class="in_type">';
												str += '							<img alt="" src="http://res.ckimg.com/sites/www/v2/images/public/kj_course/kj_'+ret.data.IcoType+'.png">';
												str += '						</div>';
												str += '						<div class="in_txt">';
												str += '							<p class="p1 f14" id="ajaxCwTitle_'+ret.data.CoursewareID+'">'+$('#title').val().substring(0, 14)+'</p>';
												str += '</p>';
												str += '						</div>';
												str += '						<div class="in_edit">';
												str += '							<a href="javascript:;" class="editCourseware" cwid="'+ret.data.CoursewareID+'">编辑</a>';
												str += '							<a target="_blank" href="/?mod=course&act=courseware&do=download&coursewareid='+ret.data.CoursewareID+authorizeUri+'">下载</a>';
												str += '							<a href="javascript:;" class="delCourseware" cwid="'+ret.data.CoursewareID+'">删除</a>';
												str += '						</div>';
												str += '		</div>';
												str += '</li>';
												$("#coursewareList").append(str);
												addCoursewareHandler();
												uploadBoxy.cancel();
												saveCourse(0);
											} else {
												alert(ret.data);
											}
										} 
									});
								};					
								
							}//endof callback
							
								
							
						});					
					
					
				}
				
			}
		});
		return false;
	});
	
	
	
	//从课件库选择

	$("#selectCourseware").click(function(){
		$.ajax({
			url:"/?mod=course&act=courseware&do=select"+authorizeUri+"&courseid="+CourseID+"&tm="+new Date().getTime(),
			type:'get',
			dataType:'html',
			success:function(ret){
				try{
					var x = eval("("+ret+")");
					if(x.code <0){
						$.ckAlert({message:x.data});
					}					
				}catch(e){
					selectCourseware("/?mod=course&act=courseware&do=select"+authorizeUri+"&courseid="+CourseID+"&tm="+new Date().getTime());
				}			
			}
		});
		
	});
	


	$("#btnSaveCourse").click(function(){
		saveCourse(0);
		return false;
	});
	
	$("#btnOnsellCourse").click(function(){
		saveCourse(1);
		return false;
	});
	
	$("#btnSaveEdit").click(function(){
		saveCourse(0);
		return false;		
	});
	
    $("a.editFinish").click(function(){
    	editFinishButton = true;
    	saveCourse(0);
		return false;
    });
	
});